package com.project.server.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.server.common.Result;
import com.project.server.dto.LoginRequest;
import com.project.server.dto.UserLoginResponse;
import com.project.server.model.User;
import com.project.server.service.UserService;
import com.project.server.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Tag(name = "用户管理")
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<UserLoginResponse> login(@RequestBody @Validated LoginRequest request) {
        return Result.success(userService.login(request));
    }

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result<Void> register(@RequestBody @Validated User user) {
        userService.register(user);
        return Result.success();
    }

    @Operation(summary = "获取用户信息")
    @GetMapping("/info")
    public Result<User> getUserInfo(HttpServletRequest request) {
        Long userId = JwtUtil.getUserIdFromRequest(request);
        return Result.success(userService.getById(userId));
    }

    @Operation(summary = "更新用户信息")
    @PutMapping("/update")
    public Result<Void> updateUserInfo(@RequestBody @Validated User user, HttpServletRequest request) {
        Long userId = JwtUtil.getUserIdFromRequest(request);
        user.setId(userId);
        userService.updateById(user);
        return Result.success();
    }

    @Operation(summary = "分页查询用户列表")
    @GetMapping("/page")
    public Result<Page<User>> page(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String phone) {
        return Result.success(userService.page(page, pageSize, username, phone));
    }

    @Operation(summary = "创建用户")
    @PostMapping
    public Result<Void> create(@RequestBody @Validated User user) {
        userService.create(user);
        return Result.success();
    }

    @Operation(summary = "更新用户")
    @PutMapping("/{id}")
    public Result<Void> update(@PathVariable Long id, @RequestBody @Validated User user) {
        user.setId(id);
        userService.updateById(user);
        return Result.success();
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        userService.removeById(id);
        return Result.success();
    }
}
